package nsfs

import (
	"GLibHac/fssystem"
	"GLibHac/tools"
	"github.com/pkg/errors"
)

type SectorStorage struct {
	fssystem.IStorageAbstract
	baseStorage fssystem.IStorage
	SectorSize  int32
	SectorCount int32
	size        int64
}

func (s *SectorStorage) ValidateSize(size int32, offset int64) error {
	if size < 0 {
		return errors.New("size must be non-negative")
	}
	if offset < 0 {
		return errors.New("offset must be non-negative")
	}
	if offset%int64(s.SectorSize) != 0 {
		return errors.Errorf("offset must be a multiple of %d", s.SectorSize)
	}
	return nil
}

func (s *SectorStorage) Read(position int64, destination []byte) (int, error) {
	if err := s.ValidateSize(int32(len(destination)), position); err != nil {
		return 0, err
	}
	return s.baseStorage.Read(position, destination)
}

func (s *SectorStorage) Size() int64 {
	return s.size
}

func NewSectorStorage(baseStorage fssystem.IStorage, sectorSize int32) *SectorStorage {
	this := &SectorStorage{
		baseStorage: baseStorage,
		SectorSize:  sectorSize,
		size:        baseStorage.Size(),
	}
	this.SectorCount = int32(tools.DivideUp(this.size, int64(sectorSize)))
	this.SizeFunc = this.Size
	this.ReadFunc = this.Read
	return this
}
